//
//  BaseUtil.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/8.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import SAMKeychain

class BaseUtil: NSObject {

    enum ImageDefaultType:Int{
        case UserImageType = 0
        case BigImageType = 1
    }
    
    static let baseUtil:BaseUtil = BaseUtil()
    
    let ISVersion9:Bool = true
    
    let ISIPhoneX:Bool = {
        
            var iphoneX:Bool = false
            if UIDevice.current.userInterfaceIdiom != UIUserInterfaceIdiom.phone{
                return iphoneX
            }
            
            if #available(iOS 11.0, *){
                let window = UIApplication.shared.delegate?.window
                //        if window. > 0{
                //            iphoneX = true
                //        }
            }
            
            return iphoneX
    }()
    
//    public cre(){
//
//
//    }
    
    /// 获取uuid
    ///
    /// - Returns:uuid
    public func getUUID() -> String{
        let query:SAMKeychainQuery = SAMKeychainQuery.init()
        query.account = "lgt"
        query.service = "lgt"
        //有存在
        do{
            try query.fetch()
            return SAMKeychain.password(forService: "lgt", account: "lgt") ?? ""
        }
        catch{
            let uuidStr = UIDevice.current.identifierForVendor?.uuidString ?? ""
            SAMKeychain.setPassword(uuidStr, forService: "lgt", account: "lgt")
            return uuidStr
        }
       // return ""
    }
    
    //md5 加密
    public func md5(strs:String) ->String!{
        let str = strs.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(strs.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        return String(format: hash as String)
    }
    
    public func getFont(size:CGFloat) -> UIFont{
        var font:UIFont
        if Double(SystemVersion) ?? 0 >= 9.0{
            font = UIFont.init(name: "PingFangSC-Regular", size: size) ?? UIFont.init(descriptor: UIFontDescriptor.init(), size: size)
        }else{
            font = UIFont.init(descriptor: UIFontDescriptor.init(), size: size)
        }
        return font
    }
    
    public func getBFont(size:CGFloat) -> UIFont{
       return UIFont.boldSystemFont(ofSize: size)
    }
    
    public func getHexColor(colorHex:Int, alpha:Double = 1.0) -> UIColor{
        let r = CGFloat((colorHex & 0xFF0000) >> 16) / 255.0
        let g = CGFloat((colorHex & 0xFF00) >> 8)  / 255.0
        let b = CGFloat((colorHex & 0xFF)) / 255.0
        return UIColor.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
    }
    
    public func getCacheSize()-> String {
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            
            // 把文件名拼接到路径中
            let path = cachePath! + ("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (key, fileSize) in floder {
                // 累加文件大小
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }
        
        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.2fM", totalCache)
    }
    
    //清除缓存
    func removeCache (){
        // 取出cache文件夹路径.如果清除其他位子的可以将cachesDirectory换成对应的文件夹
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last

        // 打印路径,需要测试的可以往这个路径下放东西
        //print(cachePath)
        // 取出文件夹下所有文件数组
        let files = FileManager.default.subpaths(atPath: cachePath!)
        
        // 点击确定时开始删除
        for p in files!{
            // 拼接路径
            let path = cachePath!.appendingFormat("/\(p)")
            // 判断是否可以删除
            if FileManager.default.fileExists(atPath: path){
                // 删除
                //                try! FileManager.default.removeItem(atPath: path)
                /*******/
                //避免崩溃
                do {
                    try FileManager.default.removeItem(atPath: path as String)
                } catch {
                    print("removeItemAtPath err"+path)
                }
            }
            
        }
        
    }
    
    static func stringConvertDate(string:String, dateFormat:String="yyyy-MM-dd HH:mm:ss") -> Date {
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date = dateFormatter.date(from: string)
        return date ?? Date()
    }
    
    static func dateConvertString(date:Date, dateFormat:String="yyyy-MM-dd HH:mm:ss") -> String {
        //let timeZone = TimeZone.init(identifier: "UTC")
        let timeZone = NSTimeZone.default
        let formatter = DateFormatter()
        formatter.timeZone = timeZone
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let date = formatter.string(from: date)
        return date
        //return date.components(separatedBy: " ").first!
    }
    
    // 转化成格式化后的日期字符串
    public func convertDateString(string: String) -> String{
        let date = BaseUtil.stringConvertDate(string: string)
        let tempString = BaseUtil.dateConvertString(date: date)
        return tempString
    }
    
    func testsss(info:Dictionary<String, Any>){
//        let filePath:String = NSHomeDirectory() + "/Documents/tfDic.plist"
//        let myArray:Array<Dictionary<String, Any>> = [info]
//        NSArray(array: myArray).write(toFile: filePath, atomically: true)
//
//        print(filePath)
//        let tfArray = NSArray(contentsOfFile:filePath)
//        print(tfArray)
        
//        let data = NSKeyedArchiver.archivedData(withRootObject: info, requiringSecureCoding: true)
//        
//        let inforesult = NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
//        print(inforesult)

    }
    
    //图片上传像素处理
    func getUploadImage(editedImage:UIImage) -> UIImage{
        var editedImageNew:UIImage = editedImage
        var imageW:CGFloat = editedImage.size.width
        var imageH:CGFloat = editedImage.size.height
        var needCrop:Bool = false
        //款高不能超过1600
        if imageW > imageH && imageW > ImageLimitMax{
            let rate = ImageLimitMax / imageW
            imageH = rate * imageH
            imageW = ImageLimitMax
            needCrop = true
        }else if imageH > imageW && imageH > ImageLimitMax{
            let rate = ImageLimitMax / imageH
            imageW = rate * imageW
            imageH = ImageLimitMax
            needCrop = true
        }
        
        if needCrop == true{
            editedImageNew = LGTOCBaseUtil.compressOriginalImage(editedImage, to: CGSize.init(width: imageW, height: imageH))
        }
        return editedImageNew
    }
    
    // MARK: 字典转字符串
    func dicValueString(_ dic:[String : Any]) -> String?{
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str
    }
    
    // MARK: 字符串转字典
    func stringValueDic(_ str: String) -> [String : Any]?{
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] {
            return dict
        }
        return nil
    }
    
   func getDictionaryFromJSONString(jsonString:String) ->Dictionary<String, Any>{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! Dictionary<String, Any>
        }
        return [:]
    }
    
    
    func setImage(imageView:UIImageView, imageUrl:String, type:ImageDefaultType=ImageDefaultType.UserImageType){
        var image:UIImage = UIImage.init()
        if type == ImageDefaultType.UserImageType{
            image = UIImage.init(named: "defaulthead")!
        }
        
        imageView.sd_setImage(with: URL.init(string: imageUrl), placeholderImage: image, options: SDWebImageOptions.retryFailed, context: nil)
    }
    
    //
    func getCookie(url:String, type:Int) -> String{
        let cookieDic = self.addCommonParam(param: [:])
        let cookieStr = LGTOCBaseUtil.addCookie(withUrl: url, data: cookieDic, type: type)
        return cookieStr
    }
    
    //设置通用参数
    func addCommonParam(param:Dictionary<String, Any>) -> Dictionary<String, Any>{
        var parameters:Dictionary<String, Any> = param
        parameters["client_code"] = BaseUtil.baseUtil.getUUID()
        let user_id = parameters["user_id"] as? Int ?? 0
        if user_id == 0{
            parameters["user_id"] = UserModel.share?.user_id ?? 0
        }
        
        let user_token:String = parameters["user_token"] as? String ?? ""
        if user_token.count == 0{
            parameters["user_token"] = UserModel.share?.user_token ?? ""
        }
        //用户类型
        let user_Type:Int = parameters["user_type"] as? Int ?? -1
        if user_Type == -1 && UserModel.share != nil{
            parameters["user_type"] = UserModel.share?.user_type ?? 0
        }
        
        parameters["channel"] = KChannel
        parameters["os"] = "2"
        //parameters["type"] = 1
        parameters["version"] = AppVersion
        parameters["time"] = Int(Date.init().timeIntervalSince1970)
        return parameters
    }
    
    static func setLabelSpecial(label:UILabel, str:String, specialStr:String, normalAttr:Dictionary<NSAttributedString.Key , Any>, specialAttr:Dictionary<NSAttributedString.Key , Any>){
        let attr:NSMutableAttributedString = NSMutableAttributedString.init(string: str)
        attr.addAttributes(normalAttr, range: NSRange.init(location: 0, length: str.count))
        let range = str.range(of: specialStr)!
        let nsrange = NSRange(range, in: str) // Range to NSRange
        attr.addAttributes(specialAttr, range: nsrange)
        label.attributedText = attr
    }
}
